# -*- coding: UTF-8 -*-

import smtplib, base64
from email.header import Header
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart

class sendmail(object):

    def __init__(self, transport_core):
        self.core = transport_core
        self.__host = self.core.config.MAIL_DEFAULT_HOST
        self.__sender = self.core.config.MAIL_DEFAULT_SENDER
        self.__username = self.core.config.MAIL_DEFAULT_USERNAME
        self.__sendername = self.core.config.MAIL_SENDER_NAME if hasattr(self.core.config, 'MAIL_SENDER_NAME') else self.core.config.MAIL_DEFAULT_SENDER
        self.__password = ''.join([str(chr(int(i))) for i in base64.b64decode(self.core.config.MAIL_DEFAULT_PWD).split('.')])

    def __call__(self, receiverList, title, content, imagepaths = []):
        content = '<html><head></head><body>%s</body></html>' % content
        message = MIMEMultipart()
        message['Subject'] = Header(title, 'utf-8')
        message['From'] = Header(self.__sendername, 'utf-8')
        message['To'] =  Header(','.join(receiverList), 'utf-8')
        message.attach(MIMEText(content, 'html', 'utf-8'))

        if imagepaths:
            for path in imagepaths:
                with open(path, 'rb') as f:
                    attachment = MIMEImage(f.read(), _subtype = 'octet-stream')
                    attachment.add_header('Content-Disposition', 'attachment', filename = ('gbk', '', path[path.rfind('/') + 1:]))
                    message.attach(attachment)
        try:
            smtp = smtplib.SMTP()
            smtp.connect(self.__host)
            smtp.login(self.__username, self.__password)
            smtp.sendmail(self.__sender, receiverList, message.as_string())
            return self.core.lib.outputobj(True, '发送成功')
        except Exception, e:
            return self.core.lib.outputobj(False, '发送失败：%s' % str(e))
        finally:
            smtp.quit()
